package com.gack.helper.aspect;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.gack.business.fkbModel.input.BasicInput;
import com.gack.business.fkbModel.output.FKBOutput;
import com.gack.helper.common.config.FKBConfig;
import com.gack.helper.common.util.MD5;

@Aspect
@Component
public class FKBControllerAspect {

	private final static Logger LOGGER = LoggerFactory.getLogger(FKBControllerAspect.class);
	
	@Around("execution(* com.gack.business.controller.FKBController.*(..))")
	public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable{

		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes sra = (ServletRequestAttributes) ra;
		HttpServletRequest request = sra.getRequest();
		
		Object[] args = pjp.getArgs();
		if(args.length == 0){
			LOGGER.error("费控宝token验证失败,验证参数为空。URL=" + request.getRequestURL());
			FKBOutput output = new FKBOutput();
			output.setStatus(0);
			output.setMessage("费控宝token验证失败");
			output.setData(null);
			return output;
		}
		
		BasicInput input = (BasicInput)args[0];
		String appid = input.getAppid();
		String time = input.getTime();
		String token = input.getToken();//token = (appid+appkey+time组成字符串，再用MD5加密出32位长度的字符串，字符串为小写)
		
		if(StringUtils.isBlank(appid) || StringUtils.isBlank(time) || StringUtils.isBlank(token)){
			LOGGER.error("费控宝token验证失败,验证参数为空。URL=" + request.getRequestURL() + "。appid=" + appid + "&time=" + time + "&token=" + token);
			FKBOutput output = new FKBOutput();
			output.setStatus(0);
			output.setMessage("费控宝token验证失败");
			output.setData(null);
			return output;
		}

		String appkey = FKBConfig.FKBAppKey;
		String myToken = MD5.md5(appid+appkey+time).toLowerCase();
		
		if(token.equals(myToken)){
			Object object = pjp.proceed();
			return object;
		}else{
			LOGGER.error("费控宝token验证失败。URL=" + request.getRequestURL() + "。appid=" + appid + "&time=" + time + "&token=" + token + "&appkey=" + appkey + "&myToken=" + myToken);
			FKBOutput output = new FKBOutput();
			output.setStatus(0);
			output.setMessage("费控宝token验证失败");
			output.setData(null);
			return output;
		}
	}
	
}
